//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package triger_impl

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/triger_dao"
	"atomgit.com/openlinksaas-org/api-server/triger_impl/atomgit_triger"
	"atomgit.com/openlinksaas-org/api-server/triger_impl/core"
	"atomgit.com/openlinksaas-org/api-server/triger_impl/gitcode_triger"
	"atomgit.com/openlinksaas-org/api-server/triger_impl/gitee_triger"
	"atomgit.com/openlinksaas-org/api-server/triger_impl/gitlab_triger"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_triger_api"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/mongo"
	"go.uber.org/zap"
)

var TrigerRunnerList []core.TrigerRunner = []core.TrigerRunner{}

func Init(group *gin.RouterGroup, logger *zap.Logger) {
	runerList := []core.TrigerRunner{
		atomgit_triger.NewAtomGitTrigerRunner(),
		gitcode_triger.NewGitCodeTrigerRunner(),
		gitee_triger.NewGiteeTrigerRunner(),
		gitlab_triger.NewGitlabTrigerRunner(),
		//TODO
	}
	for _, runner := range runerList {
		runner.Init(group, queryHandler, msgHandler, logger)
	}

	TrigerRunnerList = runerList
}

func queryHandler(ctx context.Context, trigerTypeId, trigerId string) (*core.TrigerConfigInfo, bool) {
	trigerItem, err := triger_dao.TrigerInfoDao.Get(ctx, "", trigerId)
	if err != nil {
		return nil, false
	}

	return &core.TrigerConfigInfo{
		TrigerId:  trigerItem.TrigerId,
		ProjectId: trigerItem.ProjectId,
		Secret:    trigerItem.Secret,
	}, true
}

func msgHandler(ctx context.Context, projectId string, msgInfo *project_triger_api.TrigerMsgInfo, logger *zap.Logger) error {
	//保存数据
	err := saveMsg(ctx, projectId, msgInfo)
	if err != nil {
		return err
	}
	return nil
}

func saveMsg(ctx context.Context, projectId string, msgInfo *project_triger_api.TrigerMsgInfo) error {
	dbSess, err := dao.StartSession()
	if err != nil {
		return err
	}
	defer dao.EndSession(dbSess)

	_, err = dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = triger_dao.MsgIndexDao.Insert(sessCtx, &triger_dao.MsgIndexDbItem{
			MsgId:     msgInfo.MsgId,
			TrigerId:  msgInfo.TrigerId,
			TimeStamp: msgInfo.TimeStamp,
			AttrList:  msgInfo.AttrList,
		})
		if err != nil {
			return nil, err
		}
		recordId := triger_dao.GenMsgRecordId(msgInfo.TrigerId, msgInfo.MsgId)
		err = triger_dao.MsgContentDao.Insert(sessCtx, &triger_dao.MsgContentDbItem{
			RecordId: recordId,
			TrigerId: msgInfo.TrigerId,
			Content:  string(msgInfo.Content),
		})
		if err != nil {
			return nil, err
		}
		count, err := triger_dao.MsgIndexDao.Count(sessCtx, msgInfo.TrigerId, false, []string{})
		if err != nil {
			return nil, err
		}
		err = triger_dao.TrigerInfoDao.UpdateMsgCount(sessCtx, projectId, msgInfo.TrigerId, count)
		if err != nil {
			return nil, err
		}
		return nil, nil
	})
	if err != nil {
		return err
	}
	return nil
}
